package com.whub507.msgmanager.task;

import com.whub507.msgmanager.domain.Message;
import com.whub507.msgmanager.service.MessageService;
import com.whub507.msgmanager.utils.TimeUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;

@Service
public class ScheduledTaskManager {

    @Resource
    DynamicScheduledTaskRegistrar dynamicScheduledTaskRegistrar;

    @Resource
    MessageService messageService;


    /**
     * 新增任务
     */
    public void add(String taskName, Message message) throws ParseException {
        String cron= TimeUtils.dateString2Cron(message.getSenttime());
//        System.out.println(cron);
        Boolean result = dynamicScheduledTaskRegistrar.addCronTask(taskName,cron,() -> runTask(taskName,message));
    }

    public void add(String taskName,String time) throws ParseException {
        String cron= TimeUtils.dateString2Cron(time);
        Boolean result = dynamicScheduledTaskRegistrar.addCronTask(taskName,cron,() -> runTask(taskName));
    }

    /**
     * 更新任务
     */
    public void update(String taskName,Message message) throws ParseException {
        cancel(taskName);
        add(taskName,message);
    }

    /**
     * 取消任务
     * @param taskName
     */
    public void cancel(String taskName){
        dynamicScheduledTaskRegistrar.cancelCronTask(taskName);
    }

    private void runTask(String taskName,Message message){
        messageService.sentMsg(message);
    }

    private void runTask(String taskName){
        System.out.println("************************************************"+taskName);
    }

}